package com.freecycle.sg.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

import com.freecycle.sg.http.HTTPManager;
import com.freecycle.sg.http.HTTPResponseHandler;
import com.freecycle.sg.sqlite.Freebie.ReferenceData;

public class ReferenceHelper {
	
	private static final String TAG = "ReferenceHelper";

	public static boolean hasDownloadedRefData(final Context context) {
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(context);
		return sp.getBoolean(Config.IS_REF_DATA_AVAILABLE, false);
	}

	private static void setDownloadedRefData(final Context context) {
		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... voids) {
				SharedPreferences sp = PreferenceManager
						.getDefaultSharedPreferences(context);
				sp.edit().putBoolean(Config.IS_REF_DATA_AVAILABLE, true)
						.commit();
				return null;
			}
		}.execute();
	}
	
	public static void downloadRefData(final Activity mActivity) {
		final ContentResolver resolver = mActivity.getContentResolver();
		
		HTTPResponseHandler handler = new HTTPResponseHandler(mActivity){
			@Override
			public void onSuccess(JSONObject object) {
				try {
					Log.v(TAG, object.toString(2));
					JSONObject json = new JSONObject(
							JSONUtils.getStringIfExist(
									Config.REF_CATEGORIES, object));
					
					// TODO input reference here
					HashMap<String, String> map = JSONUtils.convertHashMap(json);
					Set<String> keys = map.keySet();
					
					ArrayList<ContentValues> values = new ArrayList<ContentValues>();
					for (String key : keys) {
						ContentValues temp = new ContentValues();
						temp.put(ReferenceData.REF_DATA_TYPE, "categories");
						temp.put(ReferenceData.ABBREVIATION, key);
						
						JSONObject valueJSON = new JSONObject(map.get(key));
						temp.put(ReferenceData.NAME, JSONUtils.getStringIfExist("name", valueJSON));
						temp.put(ReferenceData.MARKER_URL, JSONUtils.getStringIfExist("marker", valueJSON));
						
						values.add(temp);
					}
					resolver.bulkInsert(ReferenceData.CONTENT_URI, values.toArray(new ContentValues[]{}));
					Log.v(TAG, "insert successfully " + values.size() + " reference records");
					
					setDownloadedRefData(mActivity);
				} catch (JSONException e) {
					Log.e(TAG, e.toString());
				}
			}
		};
		
		HTTPManager.post(Config.getRefDataUri, null, handler);
	}
	
}
